#!/bin/sh

#Note this is replaced by make install, not configure!
export MX_MODULE_DIR=@mx_module_dir@

VERBOSE=yes
[ -f /etc/rc.conf ] && . /etc/rc.conf

set -e

if test ! -d ${MX_MODULE_DIR}; then
    if [ "$VERBOSE" != no ]; then 
	echo "Something bad happened with the install script"
	echo "MX_DIR isn't pointing to a valid directory"
    fi
    exit 1
fi


# Remove the MX modules if loaded
unload_mx() {
    ${MX_MODULE_DIR}/mx_stop_mapper

    if /sbin/kldstat | grep 'mx_linux.ko' > /dev/null; then
	/sbin/kldunload mx_linux
    fi
	
    if /sbin/kldstat | grep 'mx_driver.ko' > /dev/null; then
	if [ "$VERBOSE" != no ]; then 
	    echo "Removing mx driver"
	fi
	/sbin/kldunload mx_driver
    fi
	
    if /sbin/kldstat | grep 'mx_mcp.ko' > /dev/null; then
	if [ "$VERBOSE" != no ]; then 
	    echo "Removing mx mcp"
	fi
	/sbin/kldunload mx_mcp
    fi
}

# Remove the GM module if loaded
unload_gm() {
    if /sbin/kldstat | grep 'gm.ko' > /dev/null; then
	if [ "$VERBOSE" != no ]; then 
	    echo "Removing gm driver"
	fi
	/usr/local/etc/rc.d/gm stop
    fi
}

# Load the MX modules
load_mx() {
    if [ "$VERBOSE" != no ]; then 
	echo "Loading mx driver"
    fi
    /sbin/kldload ${MX_MODULE_DIR}/mx_mcp.ko
    /sbin/kldload ${MX_MODULE_DIR}/mx_driver.ko
    #/sbin/kldload ${MX_MODULE_DIR}/mx_linux.ko
    #${MX_MODULE_DIR}/mx_start_mapper
}


case "$1" in
    start|"")
	unload_gm
	load_mx
	;;
    stop)
	unload_mx
	;;
    start-mapper)
	${MX_MODULE_DIR}/mx_start_mapper
	;;
    stop-mapper)
	${MX_MODULE_DIR}/mx_stop_mapper
	;;
    status)
	if /sbin/kldstat | grep 'mx_driver.ko' > /dev/null; then
	    echo "MX driver is loaded"
	else
	    echo "MX driver is not loaded"
	fi
	;;
    restart)
	unload_gm
	unload_mx
	load_mx
	;;
    *)
	echo $"Usage: $0 {start|stop|start-mapper|stop-mapper|status|restart}"
        exit 1
esac

exit 0
